package secondriver.aboxlibrary.utils;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Point;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;

/**
 * Author : secondriver
 * Created : 2015/12/8
 */
public class DisplayUtil {
    /**
     * Dip转Px
     *
     * @param context
     * @param dipValue
     * @return
     */
    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    /**
     * Px转Dip
     *
     * @param context
     * @param pxValue
     * @return
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 获取屏幕宽和高，单位px
     *
     * @param context
     * @return
     */
    public static Point screenMetrics(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return new Point(dm.widthPixels, dm.heightPixels);
    }

    /**
     * 基于测量模式计算尺寸
     *
     * @param measureSpec 测量模式
     * @param defaultSize 默认尺寸，单位像素
     * @param resources   资源对象
     * @return 测量后的尺寸，单位dip
     */
    public static int measure(int measureSpec, int defaultSize, Resources resources) {
        int result = (int) (resources.getDisplayMetrics().density * defaultSize);
        int specMode = View.MeasureSpec.getMode(measureSpec);
        int specSize = View.MeasureSpec.getSize(measureSpec);
        switch (specMode) {
            case View.MeasureSpec.UNSPECIFIED:
                return result;
            case View.MeasureSpec.AT_MOST:
                return Math.min(result, specSize);
            case View.MeasureSpec.EXACTLY:
                return specSize;
            default:
                throw new IllegalArgumentException("measureSpec is invalid .");
        }
    }


    public static Point getWindowSize(Context context) {
        Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        return size;
    }


    public static int makePressColor(int color,int alpha) {
        int r = (color >> 16) & 0xFF;
        int g = (color >> 8) & 0xFF;
        int b = (color >> 0) & 0xFF;
        r = (r - 30 < 0) ? 0 : r - 30;
        g = (g - 30 < 0) ? 0 : g - 30;
        b = (b - 30 < 0) ? 0 : b - 30;
        return Color.argb(alpha, r, g, b);
    }
}
